package com.wunong.smart.collection.domain.state.operation.impl;

import com.wunong.smart.collection.application.context.CollectionContext;
import com.wunong.smart.collection.application.request.CollectRequest;
import com.wunong.smart.collection.client.enums.CollectionStatusEnum;
import com.wunong.smart.collection.domain.model.CollectionDomain;
import com.wunong.smart.collection.domain.state.operation.AbstractCollectionOperation;
import com.wunong.smart.domain.platform.common.BizSource;
import com.wunong.smart.domain.platform.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 收藏
 *
 * @author create by zealot.zt
 */
@Slf4j
@Component
public class DoCollectOperation extends AbstractCollectionOperation<CollectRequest> {

    @Override
    protected void beforeOperate(CollectionContext<CollectRequest> context) {
        if (!collectionStateService.canCollect(context)) {
            throw new ServiceException("暂不支持收藏");
        }
    }

    @Override
    protected Object doOperate(CollectionContext<CollectRequest> context) {
        CollectionDomain domain = context.getDomain();

        // 已收藏，直接返回
        if (domain.isCollecting()) {
            log.info("user do collect skip, userId:{}, collectId:{}", domain.getUserId(), domain.getId());
            return domain.getId();
        }

        CollectRequest request = context.getRequest();

        // 业务来源信息
        BizSource source = request.getSource();
        domain.setSource(source);

        // 更新基础信息
        domain.setStatusEnum(CollectionStatusEnum.COLLECTING);

        // 设置用户信息
        domain.setUser(request.getUser());
        domain.setCollectType(request.getCollectType());

        // 保存域信息
        Long id = collectionRepository.save(domain);
        log.info("user do collect success, userId:{}, collectId:{}", domain.getUserId(), id);
        return id;
    }

    @Override
    public Class<CollectRequest> getRequestClass() {
        return CollectRequest.class;
    }

}
